package com.liveinstars.gateway.application.filter.factory;

import com.alibaba.fastjson.JSON;
import com.liveinstars.gateway.business.service.AuthService;
import com.liveinstars.api.dto.SignDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;

/**
 * 用于app在启动时先进行密钥双向核对，后期请求中进行动态改变验证的，安全性高
 */
public class RsaAuthGatewayFilterFactory extends AbstractAuthGatewayFilterFactory<RsaAuthGatewayFilterFactory.Config> {

    @Autowired
    @Qualifier("appAuthService")
    private AuthService authService;

    public RsaAuthGatewayFilterFactory() {
        super(RsaAuthGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(RsaAuthGatewayFilterFactory.Config config) {
        return (exchange, chain) -> super.auth(exchange, chain);
    }

    public static class Config {

    }

    @Override
    SignDTO getSign(ServerWebExchange exchange) {
        List<String> list = exchange.getRequest().getHeaders().get("Authorization");
        String sign = exchange.getRequest().getHeaders().get("Authorization").get(0);
        //传root可以免签，用于测试
        if("root".equals(sign)){
            SignDTO signDTO = new SignDTO();
            signDTO.setSecretKeyVersion(99);
            signDTO.setSign("");
            return signDTO;

        }else {
            SignDTO signDTO = JSON.parseObject(sign, SignDTO.class);
            return signDTO;
        }
    }

    @Override
    boolean validateSign(SignDTO sign) throws Exception{
        try {
            //设置一个免签的通道方便测试
            if(sign.getSecretKeyVersion().equals(99)){
                return true;
            }
            boolean result = authService.validateSign(sign.getSign(), sign.getSecretKeyVersion());
            return result;
        } catch (Exception e) {
            throw e;
        }
    }
}
